﻿//给QMS排故单提交军检或排故结果提交军检的数据
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:Longb
//create Date:2023-04-17
//Rewriter:
//Rewrite Date:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UFC.Common;
using UFC.DBUtility;
using System.Data;
using System.Text.RegularExpressions;
using System.Collections;
using System.Xml;

namespace MESQualityHistoryRecord
{
    class SendZSGJCheckSubmitBillToQms
    {
        private const string GJCheckSubmitBill_XmlFileds = "zsgjcheckSubmitBillNo,mfgOrderName,engineNo,engineFamily,productType,gjcheckFinishDate,isqualified,status,createEmployeeFullName,createDate,submitEmployeeFullName,submitDate,discoverProplem,takeMeasures,affiliatedFactory,checkCustomer,productName,productDescription";
        private static NewMesToQms.unifiedFunApi mtq = new NewMesToQms.unifiedFunApi();

        public void Excute()
        {
            DataTable dt = GetGJCheckSubmitBill();
            foreach (DataRow row in dt.Rows)
            {
                var resQxml = CreateXMLForGJCheckSubmitBill(GJCheckSubmitBill_XmlFileds, row);
                LogHelp.WriteLog("故检提交单提交军检-推送XMl:" + resQxml);
                var resPxml = mtq.mesToQmsAPI(resQxml);
                LogHelp.WriteLog("故检提交单提交军检-返回XMl:" + resPxml);
                Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                        {"ParentId",row["ZSGJCHECKSUBMITBILLID"].ToString ()},{"RecordType","QMS_GJCheckSubmitBill"},
                        {"ContainerID",""},{"ContainerName",""},
                        {"ProductName",row["MFGORDERNAME"].ToString()},{"WorkflowStepName",""},
                        {"SendXml",resQxml},{"ResXml",resPxml}
                    };
                XmlDocument myxml = new XmlDocument();
                myxml.LoadXml(resPxml);
                string xml = myxml.SelectSingleNode("RespMsg/document").InnerText;
                myxml.LoadXml(xml);
                string success = myxml.SelectSingleNode("TETTYP/RTYPE").InnerText;//
                string message = myxml.SelectSingleNode("TETTYP/RTMSG").InnerText;//
                if (!string.IsNullOrWhiteSpace(success) && success == "S")
                {
                    recordPara.Add("IsSuccess", "0");//成功
                }
                else
                {
                    recordPara.Add("IsSuccess", "1");//失败
                }
                OracleDAL.InserOtherSystemRecord(recordPara);
            } 
        }

        private DataTable GetGJCheckSubmitBill()
        {
            try
            {
                var strSql = @"SELECT DISTINCT gj.ZSGJCHECKSUBMITBILLID,gj.ZSGJCHECKSUBMITBILLNO,m.MFGORDERNAME,ua.ATTRIBUTEVALUE engineNO,pf.productfamilyname engineFamily,gj.PRODUCTTYPE ,to_char(gj.GJCHECKFINISHDATE,'yyyy-MM-dd hh24:mi:ss') GJCHECKFINISHDATE, 
                            gj.ISQUALIFIED,gj.STATUS,e.EMPLOYEENAME createEmployeeFullName,to_char(gj.CREATEDATE,'yyyy-MM-dd hh24:mi:ss') createDate,
                            e2.EMPLOYEENAME submitEmployeeFullName,to_char(gj.submitDate,'yyyy-MM-dd hh24:mi:ss')submitDate,gj.DISCOVERPROPLEM ,gj.TAKEMEASURES,
                            p2.PRODUCTNAME,p3.description productDescription,u.ATTRIBUTEVALUE affiliatedFactory  
                            FROM ZSGJCheckSubmitBill gj
                            LEFT JOIN MFGORDER m ON m.MFGORDERID =gj.MFGORDERID 
                            LEFT JOIN EMPLOYEE e ON e.EMPLOYEEID =gj.CREATEEMPLOYEEID 
                            LEFT JOIN EMPLOYEE e2 ON e2.EMPLOYEEID =gj.SUBMITEMPLOYEEID
                            LEFT JOIN USERATTRIBUTE ua ON ua.PARENTID = m.MFGORDERID AND ua.USERATTRIBUTENAME = '发动机'
                            LEFT JOIN PRODUCT p ON p.PRODUCTID =m.PRODUCTID 
                            LEFT JOIN PRODUCT p3 ON p3.PRODUCTBASEID =nvl(m.PRODUCTBASEID,p.PRODUCTBASEID)
                            LEFT JOIN PRODUCTBASE p2 ON p2.PRODUCTBASEID =p3.PRODUCTBASEID
                            LEFT JOIN workflow wf ON wf.workflowid=p3.workflowid
                            LEFT JOIN workflowbase wb ON wb.workflowbaseid=wf.workflowbaseid
                            LEFT JOIN workflowproductfamilylist wff ON wff.workflowid=wf.workflowid
                            LEFT JOIN productfamily pf ON pf.productfamilyid=wff.productfamilylistid
                            LEFT JOIN USERATTRIBUTE u ON u.PARENTID =m.FACTORYID AND u.USERATTRIBUTENAME ='分厂代码'
                            left join WritetoOtherSystem ws on ws.parentid=gj.ZSGJCHECKSUBMITBILLID and ws.recordtype='QMS_GJCheckSubmitBill' 
                            WHERE ws.parentid is null and rownum<500 and m.MFGORDERNAME LIKE 'ZS2023%'";
                DataSet myDS = OracleHelper.Query(strSql);
                if (myDS == null)
                {
                    return null;
                }
                if (myDS.Tables.Count == 0)
                {
                    return null;
                }
                return myDS.Tables[0];
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        private string CreateXMLForGJCheckSubmitBill(string strList, DataRow row)
        {
            XmlDocument doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
            XmlNode ReqNode = doc.CreateElement("ReqMsg");
            XmlNode headerNode = doc.CreateElement("header");
            XmlNode senderNode = doc.CreateElement("sendSysName");
            senderNode.InnerText = "APP_MES";
            XmlNode rcvNode = doc.CreateElement("rcvSysName");
            rcvNode.InnerText = "APP_QMS";
            XmlNode extNode = doc.CreateElement("extConfig");
            extNode.AppendChild(doc.CreateElement("isReTry"));
            extNode.LastChild.InnerText = "false";
            extNode.AppendChild(doc.CreateElement("FunName"));
            extNode.LastChild.InnerText = "MES_Send_Service";
            headerNode.AppendChild(senderNode);
            headerNode.AppendChild(rcvNode);
            headerNode.AppendChild(extNode);
            ReqNode.AppendChild(headerNode);

            XmlNode root = doc.CreateElement("root");
            XmlNode qmsFun = doc.CreateElement("qmsFunName");
            qmsFun.InnerText = "QMS_Send_ZSGJCheckSubmitBill_Service";
            root.AppendChild(qmsFun);

            XmlNode documentNode = doc.CreateElement("document");
            ReqNode.AppendChild(documentNode);

            XmlNode qmsDocument = doc.CreateElement("qmsDocument");//具体业务内容
            foreach (string _key in strList.Split(','))
            {
                XmlNode mainData = doc.CreateElement(_key);
                mainData.InnerText = row.Table.Columns.Contains(_key) ? row[_key].ToString() : null;
                qmsDocument.AppendChild(mainData);
            }
            XmlNode docDocument = doc.CreateElement("DocumentList");
            XmlNode FileID = doc.CreateElement("fileID");
            XmlNode FileName = doc.CreateElement("fileName");
            docDocument.AppendChild(FileID);
            docDocument.AppendChild(FileName);
            qmsDocument.AppendChild(docDocument);

            root.AppendChild(qmsDocument);
            documentNode.AppendChild(doc.CreateCDataSection("<root>" + root.InnerXml + "</root>"));
            doc.AppendChild(ReqNode);
            return doc.InnerXml;
        }
    }
}
